<?php
define('APP_PATH', __DIR__ . '/../application/');
define('THINK_PATH', __DIR__ . '/../thinkphp/');
require THINK_PATH . 'base.php';
\think\App::initCommon();

use think\Db;

echo "Starting permission update...\n";

// 1. 查找父规则 ID
$parentRule = Db::name('auth_rule')->where('name', 'order/order')->find();
if (!$parentRule) {
    die("Error: Parent rule 'order/order' not found.\n");
}
$pid = $parentRule['id'];
echo "Parent rule ID: $pid\n";

// 2. 定义新规则
$newRules = [
    [
        'name' => 'order/order/getRefundQrcode',
        'title' => '获取退款二维码',
        'type' => 'file',
        'status' => 'normal',
        'pid' => $pid,
        'ismenu' => 0,
        'createtime' => time(),
        'updatetime' => time()
    ],
    [
        'name' => 'order/order/refund',
        'title' => '直接退款',
        'type' => 'file',
        'status' => 'normal',
        'pid' => $pid,
        'ismenu' => 0,
        'createtime' => time(),
        'updatetime' => time()
    ]
];

$addedRuleIds = [];
$sqls = [];

foreach ($newRules as $ruleData) {
    // 检查是否存在
    $exist = Db::name('auth_rule')->where('name', $ruleData['name'])->find();
    if (!$exist) {
        $id = Db::name('auth_rule')->insertGetId($ruleData);
        echo "Added rule: {$ruleData['name']} (ID: $id)\n";
        $addedRuleIds[] = $id;
        
        // 生成 SQL
        $cols = implode('`, `', array_keys($ruleData));
        $vals = implode("', '", array_values($ruleData));
        $sqls[] = "INSERT INTO `fa_auth_rule` (`$cols`) VALUES ('$vals');";
    } else {
        echo "Rule already exists: {$ruleData['name']} (ID: {$exist['id']})\n";
        $addedRuleIds[] = $exist['id'];
    }
}

// 3. 更新用户组权限
$groupIds = [2, 3]; // 城市用户, 学校用户

foreach ($groupIds as $gid) {
    $group = Db::name('auth_group')->where('id', $gid)->find();
    if ($group) {
        $currentRules = explode(',', $group['rules']);
        $newRulesStr = $group['rules'];
        $updated = false;
        $addedIdsStr = "";
        
        foreach ($addedRuleIds as $rid) {
            if (!in_array($rid, $currentRules)) {
                $newRulesStr .= ',' . $rid;
                $addedIdsStr .= "," . $rid;
                $updated = true;
            }
        }
        
        if ($updated) {
            Db::name('auth_group')->where('id', $gid)->update(['rules' => $newRulesStr]);
            echo "Updated rules for group ID $gid (Added: " . trim($addedIdsStr, ',') . ")\n";
            
            // 生成 SQL (简化版，实际执行时需要 CONCAT)
            $sqls[] = "-- Update group $gid: Add rules " . trim($addedIdsStr, ',');
            $sqls[] = "UPDATE `fa_auth_group` SET `rules` = CONCAT(`rules`, '" . $addedIdsStr . "') WHERE `id` = $gid;";
        } else {
            echo "Group ID $gid already has permissions\n";
        }
    } else {
        echo "Group ID $gid not found\n";
    }
}

echo "\nGenerated SQL Statements:\n";
echo implode("\n", $sqls) . "\n";
